package de.unistuttgart.iaas.interaction.mail.util;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import de.unistuttgart.iaas.interaction.mail.util.ConfigFileHandler;
import de.unistuttgart.iaas.interaction.mail.MailAuthenticator;

/**
 * This class is an error handler. It handles errors in the connection with database and services. 
 * @author Lina Sun
 *
 */
@SuppressWarnings("restriction")
public class ErrorHandler
{
	private static Logger logger = Logger.getLogger(ErrorHandler.class);
	private static final String dbConnError = "Database Connection failed! Please check the connection!";
	private static final String sqlError = "SQL failure.Please check the database!";
	private static final String getRequestError = "Failure in GetRequest Service!";

/**
 * 	This method handles the error by the connection with database.
 *  send a mail to administrator
 * @param session
 * @param config
 * @param e
 * @throws AddressException
 * @throws MessagingException
 */
	public static void sendErrorMessageForConnDB(Session session, ConfigFileHandler config, Exception e) throws AddressException, MessagingException
	{    	
   	    	
    	String adminAddress = config.getMailAddress();
    	String sendHost = config.getSendHost();
    	String username = config.getUsername();
    	String password = config.getPassword();
    	int sendPort = config.getSendPort();
    	
    	
	    // create properties
	    Properties properties = System.getProperties();

	    // set hostname for properties
	    properties.setProperty("mail.smtp.host", sendHost);

	    // set port for properties
	    properties.setProperty("mail.smtp.port", String.valueOf(sendPort));

	    // In general, authentication information will be asked, 
	    //so this will be set in the properties 
	    properties.setProperty("mail.smtp.auth", "true");


	    MimeMessage msgAdmin = new MimeMessage(session);

	    
	    msgAdmin.setFrom(new InternetAddress(adminAddress));
	    msgAdmin.setRecipients(Message.RecipientType.TO, InternetAddress.parse(adminAddress, false));
	    msgAdmin.setSubject(dbConnError);
	    msgAdmin.setText(dbConnError+"\nError:\n"+e.getStackTrace());
	    
	    Transport transport = session.getTransport("smtp"); 
	    transport.connect(sendHost,username,password); 
	    transport.send(msgAdmin);
	    
	    logger.error("A error message for database connection to "+adminAddress+" has been sent.");
	    transport.close(); 

	}
	/**
	 * This method handles SQLException. 
	 * send a mail to administrator
	 * @param session
	 * @param config
	 * @param e
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public static  void sendErrorMessageForSQL(Session session, ConfigFileHandler config, Exception e) throws AddressException, MessagingException
	{    	
   	    	
    	String adminAddress = config.getMailAddress();
    	String sendHost = config.getSendHost();
    	String username = config.getUsername();
    	String password = config.getPassword();
    	int sendPort = config.getSendPort();
    	
      	
	    // create properties
	    Properties properties = System.getProperties();

	    // set hostname for properties
	    properties.setProperty("mail.smtp.host", sendHost);

	    // set port for properties
	    properties.setProperty("mail.smtp.port", String.valueOf(sendPort));

	    // In general, authentication information will be asked, 
	    //so this will be set in the properties 
	    properties.setProperty("mail.smtp.auth", "true");


	    MimeMessage msgAdmin = new MimeMessage(session);

	    
	    msgAdmin.setFrom(new InternetAddress(adminAddress));
	    msgAdmin.setRecipients(Message.RecipientType.TO, InternetAddress.parse(adminAddress, false));
	    msgAdmin.setSubject(sqlError);
	    msgAdmin.setText(sqlError+"\nError:\n"+e.getStackTrace());
	    
	    Transport transport = session.getTransport("smtp"); 
	    transport.connect(sendHost,username,password); 
	    transport.send(msgAdmin);
	    
	    logger.error("A error message for database connection to "+adminAddress+" has been sent.");
	    transport.close(); 

	}
	/**
	 * This method handles the error in GetRequest Service.
	 * @param session
	 * @param config
	 * @param e
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public static  void sendErrorMessageForGetRequest(Session session, ConfigFileHandler config, Exception e) throws AddressException, MessagingException
	{    	
   	    	
    	String adminAddress = config.getMailAddress();
    	String sendHost = config.getSendHost();
    	String username = config.getUsername();
    	String password = config.getPassword();
    	int sendPort = config.getSendPort();
    	    	
	    // create properties
	    Properties properties = System.getProperties();

	    // set hostname for properties
	    properties.setProperty("mail.smtp.host", sendHost);

	    // set port for properties
	    properties.setProperty("mail.smtp.port", String.valueOf(sendPort));

	    // In general, authentication information will be asked, 
	    //so this will be set in the properties 
	    properties.setProperty("mail.smtp.auth", "true");


	    MimeMessage msgAdmin = new MimeMessage(session);

	    
	    msgAdmin.setFrom(new InternetAddress(adminAddress));
	    msgAdmin.setRecipients(Message.RecipientType.TO, InternetAddress.parse(adminAddress, false));
	    msgAdmin.setSubject(getRequestError);
	    msgAdmin.setText(getRequestError+"\nError:\n"+e.getStackTrace());
	    
	    Transport transport = session.getTransport("smtp"); 
	    transport.connect(sendHost,username,password); 
	    transport.send(msgAdmin);
	    
	    logger.error("A error message for database connection to "+adminAddress+" has been sent.");
	    transport.close(); 

	}

	/**
	 * This method sends a information mail to unregistered user.
	 * @param recipientAdd
	 * @param session
	 * @param config
	 * @throws AddressException
	 * @throws MessagingException
	 */
	@SuppressWarnings("static-access")
	public static void sendWarnMessageForRegister(String recipientAdd,Session session, ConfigFileHandler config) throws AddressException, MessagingException
	{    	
   	    	
    	String adminAddress = config.getMailAddress();
    	String sendHost = config.getSendHost();
    	String username = config.getUsername();
    	String password = config.getPassword();
    	int sendPort = config.getSendPort();
    	
    	String subject="E-mail is invalid, please register!";
    	String text="E-mail is invalid, please register! ";
    	
//   	 Authenticator auth = new MailAuthenticator(username,password); 
	    // create properties
	    Properties properties = System.getProperties();

	    // set hostname for properties
	    properties.setProperty("mail.smtp.host", sendHost);

	    // set port for properties
	    properties.setProperty("mail.smtp.port", String.valueOf(sendPort));

	    // In general, authentication information will be asked, 
	    //so this will be set in the properties 
	    properties.setProperty("mail.smtp.auth", "true");

	    // create a new Session object
//	    Session session = Session.getDefaultInstance(properties,auth);
	    // create a new message
	    MimeMessage msg = new MimeMessage(session);

	    // set the sender-address
	    msg.setFrom(new InternetAddress(adminAddress));

   
	    // set receiver-address
	    // Message.RecipientType.CC means CC
	    // Message.RecipientType.BCC means BCC
	    // InternetAddress.parse--Parse the given sequence of addresses into InternetAddress objects. 
	    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientAdd, false));

	    // set title
	    msg.setSubject(subject);

	    // set body
	    msg.setText(text);
	    Transport transport = session.getTransport("smtp"); 
	    transport.connect(sendHost,username,password); 
	    // send e-mail 
	    transport.send(msg);
    
	    logger.error("A warning message for register to "+recipientAdd+" has been sent.");
	    transport.close(); 

	}

}
